package com.iepacj.mina;

import org.apache.mina.core.session.IoSession;

import javax.management.*;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by iEpac on 16/6/18.
 */
public class SessionMbean implements DynamicMBean{


    private IoSession session;

    public IoSession getSession() {
        return session;
    }

    public void setSession(IoSession session) {
        this.session = session;
        this.session.setAttribute("remoteAddress", session.getRemoteAddress());
        this.session.setAttribute("sessionId", session.getId());
        this.session.setAttribute("session", session.toString());
    }

    @Override
    public Object getAttribute(String attribute) throws AttributeNotFoundException, MBeanException, ReflectionException {
        System.out.println("getAttr :: " + attribute);
        return session.getAttribute(attribute);
    }

    @Override
    public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException {
        String name = attribute.getName();
        Object value = attribute.getValue();
        System.out.println("设置attr :: " + name + " = " + value);
    }

    @Override
    public AttributeList getAttributes(String[] attributes) {
        return null;
    }

    @Override
    public AttributeList setAttributes(AttributeList attributes) {
        return null;
    }

    @Override
    public Object invoke(String actionName, Object[] params, String[] signature) throws MBeanException, ReflectionException {
        return null;
    }

    @Override
    public MBeanInfo getMBeanInfo() {

        MBeanAttributeInfo[] infos = new MBeanAttributeInfo[4];

        String mid = (String) session.getAttribute("mid");
        long id = session.getId();
        String addr = session.getRemoteAddress().toString();
        String name = mid + addr + "-" + id;
        Descriptor desc = new ImmutableDescriptor(name + "=" + session);

        MBeanAttributeInfo info = new MBeanAttributeInfo("mid", "string", "用户id", true, false, false);
        MBeanAttributeInfo address = new MBeanAttributeInfo("remoteAddress", "string", "用户IP地址", true, false, false);
        MBeanAttributeInfo sid = new MBeanAttributeInfo("sessionId", "int", "用户socket id", true, false, false);
        MBeanAttributeInfo sessionInfo = new MBeanAttributeInfo("session", "IoSession", "用户session", true, false, false);

        infos[0] = info;
        infos[1] = address;
        infos[2] = sid;
        infos[3] = sessionInfo;

        MBeanInfo mi = new MBeanInfo(SessionMbean.class.getName(), "sessionMbean", infos, null, null, null, desc);
        return mi;
    }
}






















